//
//  SignupViewController.m
//  Mine
//
//  Created by CPX on 2018/7/20.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "SignupViewController.h"
#import "MineTool.h"
#import "LoginController.h"

/**
 注册页
 @author yzl
 */
@interface SignupViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) UITextField *accountTF;
@property (nonatomic,strong) UITextField *pwdTF;

@property (nonatomic,strong) UITextField *verifyTF;

@property (nonatomic,strong) UIButton *signup;
@property (nonatomic,strong) UIButton *verify;

@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) UILabel *timerLabel;
@property (nonatomic) NSInteger timeCount;


@end

@implementation SignupViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];

    self.timeCount = 89;
    [self initUI];
}

- (void)initUI{
    UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage RTL_ImageWithName:@"login_bg"]];
    bgImg.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:bgImg];
    UIImage *image = [[UIImage imageNamed:@"login_white"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 15, 15, 15) resizingMode:UIImageResizingModeStretch];
    UIImageView *whiteImg = [[UIImageView alloc] initWithImage:image];
    whiteImg.size = CGSizeMake(300, 281);
    whiteImg.userInteractionEnabled = YES;
    whiteImg.centerX = self.view.width/2;
    whiteImg.centerY = self.view.height/2-50;
    //    whiteImg.layer.cornerRadius = 10;
    //    whiteImg.layer.masksToBounds = YES;
    [self.view addSubview:whiteImg];
    
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon90"]];
    icon.size = CGSizeMake(64, 64);
    icon.centerX = whiteImg.width/2;
    icon.layer.cornerRadius = 10;
    icon.layer.masksToBounds = YES;
    icon.centerY = 0;
    [whiteImg addSubview:icon];
    
    UILabel *label = [UILabel new];
    label.text = @"iMuslim";
    label.font = [UIFont boldSystemFontOfSize:17];
    label.textColor = UIColorHex(#001208);
    [label sizeToFit];
    label.top = icon.bottom + 5.5;
    label.centerX = icon.centerX;
    
    [whiteImg addSubview:label];
    
    UIImageView *imgv1 = [[UIImageView alloc] initWithImage:[UIImage RTL_ImageWithName:@"email_ic"]];
    [whiteImg addSubview:imgv1];
    
    [imgv1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(27);
        make.top.mas_equalTo(105);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    
    self.accountTF = [[UITextField alloc] initWithFrame:CGRectZero];
    self.accountTF.delegate = self;
    self.accountTF.placeholder = TLString(@"input_email");
    self.accountTF.font = [UIFont systemFontOfSize:15];
    [whiteImg addSubview:self.accountTF];
    [self.accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(imgv1.mas_trailing).offset(16);
        make.centerY.mas_equalTo(imgv1);
        make.height.mas_equalTo(30);
        make.trailing.mas_equalTo(whiteImg.mas_trailing).offset(-65);
    }];
    
    UIView *line1 = [UIView new];
    line1.backgroundColor = UIColorHex(#00732FAA);
    [whiteImg addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(imgv1);
        make.top.mas_equalTo(imgv1.mas_bottom).offset(9);
        make.trailing.mas_equalTo(whiteImg.mas_trailing).offset(-31.5);
        make.height.mas_equalTo(.5f);
    }];
    
    self.verify = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.verify addTarget:self action:@selector(onSendCodeTouched) forControlEvents:UIControlEventTouchUpInside];
    self.verify.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [self.verify setTitle:TLString(@"get_code") forState:UIControlStateNormal];
    [self.verify setTitleColor:UIColorHex(#FF5D03) forState:UIControlStateNormal];
    [whiteImg addSubview:self.verify];
    [self.verify mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(27);
        make.top.mas_equalTo(line1.mas_bottom).offset(24);
        make.height.mas_equalTo(18);
        make.width.mas_greaterThanOrEqualTo(10);
    }];
    
    self.verifyTF = [[UITextField alloc] initWithFrame:CGRectZero];
    self.verifyTF.keyboardType = UIKeyboardTypeNumberPad;
    self.verifyTF.delegate = self;
    [whiteImg addSubview:self.verifyTF];
//    self.pwdTF.placeholder = TLString(@"input_psd");
//    self.verifyTF.font = [UIFont systemFontOfSize:15];
    self.verifyTF.font = [UIFont boldSystemFontOfSize:15];
    [self.verifyTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(27);
        make.centerY.mas_equalTo(self.verify);
        make.height.mas_equalTo(30);
        make.trailing.mas_equalTo(whiteImg.mas_trailing).offset(-65);
    }];
    self.verifyTF.hidden = YES;
    
    self.timerLabel = [UILabel new];
    self.timerLabel.font = [UIFont systemFontOfSize:15];
    self.timerLabel.textColor = UIColorHex(#00120888);
    [whiteImg addSubview:self.timerLabel];
    [self.timerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(line1);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_equalTo(18);
        make.centerY.mas_equalTo(self.verifyTF);
    }];
    self.timerLabel.text = @"89'";
    self.timerLabel.hidden = YES;
    
    
    UIView *line11 = [UIView new];
    line11.backgroundColor = UIColorHex(#00732FAA);
    [whiteImg addSubview:line11];
    [line11 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(imgv1);
        make.top.mas_equalTo(self.verify.mas_bottom).offset(8);
        make.trailing.mas_equalTo(whiteImg.mas_trailing).offset(-31.5);
        make.height.mas_equalTo(.5f);
    }];
    
    
    UIImageView *imgv2 = [[UIImageView alloc] initWithImage:[UIImage RTL_ImageWithName:@"key_ic"]];
    [whiteImg addSubview:imgv2];
    
    [imgv2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(27);
        make.top.mas_equalTo(line11.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    
    self.pwdTF = [[UITextField alloc] initWithFrame:CGRectZero];
    self.pwdTF.delegate = self;
    self.pwdTF.keyboardType = UIKeyboardTypeASCIICapable;
    self.pwdTF.secureTextEntry = YES;
    [whiteImg addSubview:self.pwdTF];
    self.pwdTF.placeholder = TLString(@"input_psd");
    self.pwdTF.font = [UIFont systemFontOfSize:15];
    [self.pwdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(imgv2.mas_trailing).offset(16);
        make.centerY.mas_equalTo(imgv2);
        make.height.mas_equalTo(30);
        make.trailing.mas_equalTo(whiteImg.mas_trailing).offset(-65);
    }];
    
    UIView *line2 = [UIView new];
    line2.backgroundColor = UIColorHex(#00732FAA);
    [whiteImg addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(imgv2.mas_bottom).offset(9);
        make.leading.mas_equalTo(imgv2);
        make.trailing.mas_equalTo(whiteImg.mas_trailing).offset(-31.5);
        make.height.mas_equalTo(.5f);
    }];
    
    
    self.signup = [UIButton buttonWithType:UIButtonTypeCustom];
    self.signup.size = CGSizeMake(180, 44);
    [self.signup addTarget:self action:@selector(onSignupTouched) forControlEvents:UIControlEventTouchUpInside];

    self.signup.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.signup setTitle:TLString(@"sign_up") forState:UIControlStateNormal];
    self.signup.layer.cornerRadius = 22;
    self.signup.layer.masksToBounds = YES;
    [self.signup setBackgroundColor:UIColorHex(#C3C3C3)];
    self.signup.centerX = whiteImg.centerX;
    self.signup.centerY = whiteImg.bottom;
    [self.view addSubview:self.signup];
    
    UIButton *signup = [UIButton buttonWithType:UIButtonTypeCustom];
    signup.size = CGSizeMake(180, 44);
    [signup addTarget:self action:@selector(onLoginTouched) forControlEvents:UIControlEventTouchUpInside];
    signup.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [signup setTitleColor:UIColorHex(#001208) forState:UIControlStateNormal];
    [signup setTitle:TLString(@"LOGIN") forState:UIControlStateNormal];
    //    signup.layer.cornerRadius = 22;
    //    signup.layer.masksToBounds = YES;
    //    [signup setBackgroundColor:UIColorHex(#C3C3C3)];
    signup.centerX = whiteImg.centerX;
    signup.top = self.signup.bottom + 5;
    [self.view addSubview:signup];
    
//    UIButton *fbLogin = [UIButton buttonWithType:UIButtonTypeCustom];
//    //    fbLogin.size = CGSizeMake(180, 44);
//    fbLogin.titleLabel.font = [UIFont boldSystemFontOfSize:12];
//    [fbLogin setTitle:TLString(@"log_facbook") forState:UIControlStateNormal];
//    [fbLogin setImage:[UIImage RTL_ImageWithName:@"fb_logo"] forState:UIControlStateNormal];
//    [fbLogin setImage:[UIImage RTL_ImageWithName:@"fb_logo"] forState:UIControlStateHighlighted];
//    [fbLogin setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
//    [fbLogin setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
//    [fbLogin sizeToFit];
//    fbLogin.height = 44;
//    fbLogin.width += 30;
//    fbLogin.layer.cornerRadius = 22;
//    fbLogin.layer.masksToBounds = YES;
//    [fbLogin setBackgroundColor:UIColorHex(#3E64B5)];
//    fbLogin.centerX = whiteImg.centerX;
//    fbLogin.bottom = kScreenHeight-48;
//    [self.view addSubview:fbLogin];
    
    [self initNavigationBar];
}

- (void)initNavigationBar{
    [self initLeftBackNaviButton];
    
    [self.myNavigationBar.backButton setImage:[UIImage imageNamed:@"close_black_btn"] forState:UIControlStateNormal];
    [self.myNavigationBar.backButton setTitle:TLString(@"signup") forState:UIControlStateNormal];
    [self.myNavigationBar.backButton addTarget:self action:@selector(onBackTouched) forControlEvents:UIControlEventTouchUpInside];
    self.myNavigationBar.backgroundColor = [UIColor clearColor];
}

- (void)loadData{
    
}

#pragma mark - tf delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.pwdTF && string.length+textField.text.length>16) {
        return NO;
    }
    if (string.length) {
        if ((textField == self.accountTF && self.pwdTF.text.length && self.verifyTF.text.length)||(textField == self.pwdTF && self.accountTF.text.length && self.verifyTF.text.length) || (textField == self.verifyTF && self.accountTF.text.length && self.pwdTF.text.length)) {
            [self.signup setBackgroundColor:UIColorHex(#00732F)];
        }
    }
    else if(textField.text.length == range.length){
        //        if ((textField == self.accountTF && !self.pwdTF.text.length && textField.text.length == range.length) ||(textField == self.pwdTF && !self.accountTF.text.length && textField.text.length == range.length)) {
        //            [self.loginBtn setBackgroundColor:UIColorHex(#C3C3C3)];
        //        }
        [self.signup setBackgroundColor:UIColorHex(#C3C3C3)];
    }
    return true;
}

- (void)timerAction{
    self.timerLabel.text = [NSString stringWithFormat:@"%ld'",self.timeCount--];
    if (self.timeCount == 0) {
        [_timer invalidate];
        _timer = nil;
        
        self.verifyTF.hidden = YES;
        self.timerLabel.hidden = YES;
        self.verify.hidden = NO;
    }
}

#pragma mark - actions

- (void)onSendCodeTouched{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    if (self.accountTF.text.validateEmail) {
        [self.view endEditing:YES];
        [MBProgressTool showLoadingForView:self.view];
        [MineApi sendCheckCode:self.accountTF.text success:^(id response) {
            [MBProgressTool hideForView:self.view];
            self.timeCount = 89;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
            [self.timer fire];
            
            self.verify.hidden = YES;
            self.verifyTF.hidden = NO;
            self.timerLabel.hidden = NO;
            
        } failure:^(NSError *error) {
            if(error.userInfo[@"msg"]){
                [MBProgressTool showTextForView:self.view text:error.userInfo[@"msg"]];
            }
            else{
                [MBProgressTool hideForView:self.view];
            }
        }];
    }
    else{
        [MBProgressTool showTextForView:self.view text:TLString(@"input_error")];
    }
}

- (void)onSignupTouched{
    if (self.accountTF.text.validateEmail && self.verifyTF.text.isPureInt && self.pwdTF.text.length) {
        [self.view endEditing:YES];
        [MBProgressTool showLoadingForView:self.view];
        [MineApi registerWith:self.accountTF.text pwd:self.pwdTF.text code:self.verifyTF.text success:^(id response) {
            [MineTool sharedTool].userToken = response[@"token"];
            [MineTool sharedTool].username = response[@"username"];
            [MineTool sharedTool].isLogin = YES;
            [MineTool sharedTool].email = response[@"email"];
            [MineTool sharedTool].avatar = response[@"avatar"];
            [[MineTool sharedTool] saveUserInfo];
            
            [MBProgressTool hideForView:self.view];
            [MineApi registerToken:[MineTool sharedTool].fcmToken deviceId:[MineTool sharedTool].deviceId];
            [self popController];
            
        } failure:^(NSError *error) {
            [MBProgressTool showTextForView:self.view text:error.userInfo[@"msg"]];
        }];
    }
    else{
        [MBProgressTool showTextForView:self.view text:TLString(@"input_error")];
    }
}

- (void)popController{
    NSInteger index = 0;
    NSInteger targetIndex = -1;
    
    for (UIViewController *ctr in self.navigationController.viewControllers) {
        
        if ([ctr.className isEqualToString:@"LoginController"] ||
            [ctr.className isEqualToString:@"SignupViewController"]||
            [ctr.className isEqualToString:@"ResetPwdController"]) {
            targetIndex = index;
            break;
        }
        index++;
    }
    if (targetIndex >0) {
        [self.navigationController popToViewController:self.navigationController.viewControllers[targetIndex-1] animated:YES];
    }
}

- (void)onBackTouched{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)onLoginTouched{
    
    for (UIViewController *c in self.navigationController.viewControllers) {
        if ([c isKindOfClass:[LoginController class]]) {
            
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
    }
    LoginController *c = [LoginController new];
    [self.navigationController pushViewController:c animated:YES];
}

@end
